package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author shiminghui
 * @date 2024/12/3 17:31
 * @description: TODO
 */
@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Override
    @Async // 开启多线程
    public void addNewsToTask(Integer id, Date publishTime) {
        // 创建task对象
        Task task = new Task();
        // 赋值
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        //将wmNews对象转换为二进制字节,(序列化),使用谷歌的
        byte[] serialize = ProtostuffUtil.serialize(wmNews);
        task.setParameters(serialize);
        // 调用远程接口
        ResponseResult result = scheduleClient.addTask(task);
        if (result.getCode() != 200) {
            log.error("添加任务失败,文章id为{}", id);
        }
    }

    @Override
//    @Scheduled(fixedDelay = 1000) //每秒执行一次
    public void scanNewsByTask() {
        log.info("拉取任务");
        //调用远程接口,获取任务
        ResponseResult result = scheduleClient.getTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (result == null || result.getData() == null) {
            return;
        }
        // 反序列化
        String taskJsonString = JSON.toJSONString(result.getData());
        Task task = JSON.parseObject(taskJsonString, Task.class);
        if (task == null) {
            return;
        }
        byte[] parameters = task.getParameters();
        WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);

        // 审核文章
        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
    }


}
